package sf.core.service.impl;

import java.text.ParseException;
import java.util.Date;
import java.util.Optional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import com.nimbusds.jose.JOSEException;
import com.nimbusds.jose.JWSAlgorithm;
import com.nimbusds.jose.JWSHeader;
import com.nimbusds.jose.JWSSigner;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import com.nimbusds.jwt.JWTClaimsSet;
import com.nimbusds.jwt.SignedJWT;

import sf.core.exception.SugarException;
import sf.core.service.AuthService;

/**
 * Created by ligen on 16-3-11.
 */

@Service
public class AuthServiceImpl implements AuthService<Integer> {

	private static final JWSHeader JWS_HEADER = new JWSHeader(JWSAlgorithm.HS256);
	private static final String TOKEN_SECRET = "LigenLiuchengwanLiyongYuleWutunHuangshisui";
	private static final String AUTH_HEADER_KEY = "Authorization";

	@Override
	public String createToken(Integer sub, Date issueTime, Date expireTime) throws JOSEException {
		JWTClaimsSet claimsSet = new JWTClaimsSet.Builder().subject(Integer.toString(sub)).issueTime(issueTime)
				.expirationTime(expireTime).build();

		JWSSigner signer = new MACSigner(TOKEN_SECRET);
		SignedJWT jwt = new SignedJWT(JWS_HEADER, claimsSet);
		jwt.sign(signer);
		return jwt.serialize();
	}

	@Override
	public Integer getSubject(HttpServletRequest request) throws SugarException {
		Optional<String> token = Optional.ofNullable(request.getHeader(AUTH_HEADER_KEY));
		if (token.isPresent()) {
			try {
				SignedJWT signedJWT = SignedJWT.parse(token.get());
				if (signedJWT.verify(new MACVerifier(TOKEN_SECRET))) {
					return Integer.valueOf(signedJWT.getJWTClaimsSet().getSubject());
				}
			} catch (ParseException | JOSEException ex) {
				ex.printStackTrace();
			}
		}
		throw new SugarException(HttpServletResponse.SC_UNAUTHORIZED, "未授权");
	}

}
